package agriculture.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;


/**
 * 全局跨域配置 (Spring Cloud Gateway)
 */
@Configuration
public class GlobalCorsConfig {

    @Bean
    public CorsWebFilter corsWebFilter() {
        // 1. 创建 CORS 配置对象
        CorsConfiguration config = new CorsConfiguration();
        // 允许所有域名进行跨域调用 (也可改为具体域名，比如 http://localhost:5173)
        config.addAllowedOriginPattern("http://localhost:5173");
        config.addAllowedOriginPattern("http://localhost:8081");
        config.addAllowedOriginPattern("http://localhost:8082");
        
        // 允许所有请求方法：GET, POST, PUT, DELETE...
        config.addAllowedMethod("*");
        // 允许携带任何头信息
        config.addAllowedHeader("*");
        // 是否允许携带 Cookie
        config.setAllowCredentials(true);

        // 2. 注册跨域配置，对所有 URL 生效
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        // 3. 返回 CorsWebFilter，作为全局过滤器生效
        return new CorsWebFilter(source);
    }
}
